# -*- coding: utf-8 -*-

import json
import logging


def utf8_encode(sequence):
    if sequence is None:
        return None
    return sequence.encode('utf-8')


def utf8_decode(bin):
    if bin is None:
        return None
    return bin.decode('utf-8')


def get_request_content(request):
    Validator.not_null(request.body, 'request body can not be null')
    request_data = utf8_decode(request.body)
    logging.debug('request body: %s', request_data)
    Validator.not_blank(request_data, 'request body content can not be blank')
    return json.loads(request_data)


def get_request_attr(request, key):
    _dict = get_request_content(request)
    Validator.not_null(_dict, 'request body can not be null')
    return _dict.get(key)


class ParamError(ValueError):
    pass


class BussinessError(ValueError):
    pass


class Validator(object):

    @staticmethod
    def is_true(condition, msg=''):
        if not condition:
            raise ParamError(msg)

    @staticmethod
    def not_null(val, msg='val can not be null'):
        return Validator.is_true((val is not None), msg)

    @staticmethod
    def not_blank(val, msg='val can not be blank'):
        return Validator.is_true(val, msg)

    @staticmethod
    def chk_bussiness(condtion, msg=''):
        if not condtion:
            raise BussinessError(msg)
